package com.gtpickupapp;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.LightingColorFilter;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.EditText;
import android.widget.ImageView;
import android.os.Bundle;

public class gtpickupapp extends Activity {
    /** Called when the activity is first created. */
	
	public boolean validlogin = false;
	public ProgressDialog loginWaiting;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //TODO remove ---Used to fill in the login fields for debugging
        EditText u = (EditText) findViewById(R.id.txt_username);
        u.setText("thastings3");
		EditText p = (EditText) findViewById(R.id.txt_password);
        p.setText("admin");
        //
        
        //create the invalid login alert dialog
        final AlertDialog.Builder invalidLoginAlert = new AlertDialog.Builder(this);
        invalidLoginAlert.setMessage("Sorry that is an invalid Username and Password combination")
        	.setCancelable(false).setNeutralButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			});
        //end of invalid login alert dialog
        
        final Button login = (Button) findViewById(R.id.login);
        login.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0xC6930A));
        login.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View v) {
        		
        		
        		EditText username = (EditText) findViewById(R.id.txt_username);
        		EditText password = (EditText) findViewById(R.id.txt_password);
        		//Toast.makeText(gtpickupapp.this,username.getText().toString() + "\n" + password.getText().toString() , 3).show();
        		
        		Bundle bundle = new Bundle();
        		bundle.putString("uName", username.getText().toString());
        		Intent myintent = new Intent(gtpickupapp.this,MainPage.class);
        		
        		//make sure the user is a valid user
        		//need to add username to the bundle, or some other method for making a session
        		String result = "";
        		InputStream is = null;
        		String uname = username.getText().toString();
        		String pass  = password.getText().toString();
        		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        		//------------ not secure for password.. change in future. 
        		//TODO add https request for password
        		nameValuePairs.add(new BasicNameValuePair("userName" ,uname));
        		nameValuePairs.add(new BasicNameValuePair("password",pass));
        		loginWaiting = ProgressDialog.show(gtpickupapp.this,"", "Signing in...",true);
        		//http post
        		try{
        				
        		        HttpClient httpclient = new DefaultHttpClient();
        		        HttpPost httppost = new HttpPost("http://gtplay.webatu.com/login.php");
        		        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        		        HttpResponse response = httpclient.execute(httppost);
        		        HttpEntity entity = response.getEntity();
        		        is = entity.getContent();
        		}catch(Exception e){
        		        Log.e("log_tag", "Error in http connection "+e.toString());
        		}
        		
        		//convert response to string
        		try{
        		        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        		        StringBuilder sb = new StringBuilder();
        		        String line = null;
        		        while ((line = reader.readLine()) != null) {
        		                sb.append(line + "\n");
        		        }
        		        is.close();
        		 
        		        result=sb.toString();
        		}catch(Exception e){
        		        Log.e("log_tag", "Error converting result "+e.toString());
        		}
        		 
        		//parse json data
        		try{
        				//make sure the length is equal to 1. Meaning that the user is valid
        		        JSONArray jArray = new JSONArray(result);
        		        if(jArray.length() == 1){
        		        	validlogin = true;
        		        }
        		        
        		}
        		catch(JSONException e){
        		        Log.e("log_tag", "Error parsing data "+e.toString());
        		}
        		
        		myintent.putExtras(bundle);
        		//if valid then login, else show a warning that information was invalid
        		if(validlogin){
        			gtpickupapp.this.startActivity(myintent);
        			finish();
        		}else{
        			loginWaiting.cancel();
        			invalidLoginAlert.create().show();
        			password.setText("");
        			Log.e("puta","you have reached the invalid login alert area");
        		}
        		
        	}         
        });
        
        final Button signUp = (Button) findViewById(R.id.main_signup);
        signUp.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0xC6930A));
        signUp.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View v) {
        		// Perform action on click
        		EditText username = (EditText) findViewById(R.id.txt_username);
        		EditText password = (EditText) findViewById(R.id.txt_password);
        		
        		//below code is to test using a bundle to pass info from one activity to the next
        		Bundle bundle = new Bundle();
        		bundle.putString("uName", username.getText().toString());
        		
        		Intent myintent = new Intent(gtpickupapp.this,SignUp.class);
        		myintent.putExtras(bundle);
        		gtpickupapp.this.startActivity(myintent);
        		
        		finish();
        	}         
        });

        
    }
}